package com.youkun.controller;

import com.mysql.cj.x.json.JsonArray;
import com.youkun.entity.User;
import com.youkun.services.UserServices;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import java.util.Date;
import java.util.Map;

import static io.jsonwebtoken.Jwts.builder;

/**
 * Created by youkun on 2017/3/7.
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServices userServices;

    @RequestMapping(value = "/register")
    public User userRegister(@RequestBody User user){

        return userServices.sava(user);
    }

    @RequestMapping(value = "/login")
    public String userLogin(@RequestBody Map<String,String> json) throws ServletException {
        if(json.get("username")==null||json.get("password")==null){
             throw  new ServletException("用户名或密码为空");
        }
        String username = json.get("username");
        String password = json.get("password");

        User user =  userServices.findByuserName(username);
        if(user ==null){
            throw  new ServletException("用户名不存在");
        }
        String pwd = user.getPassword();
        if(!password.equals(pwd)){
            throw  new ServletException("密码错误");
        }

        return builder().setSubject(username).claim("roles","user").setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256,"secretkey").compact();
    }

}
